#!/usr/bin/python3
# -*- coding:utf-8 -*-
#python version: 3.6.7

#os用来取目录
import os

#首先获取到脚本所在目录，并把工作目录设为脚本所在目录
cdw = os.path.realpath(__file__)
cdw = os.path.dirname(cdw)
os.chdir(cdw)

f_name = __file__
if '/' in f_name:
    f_name = f_name[f_name.rindex('/') + 1: ]
elif '\\' in f_name:
    f_name = f_name[f_name.rindex('\\') + 1: ]
print(f_name.center(72, '*'))

#先搞个文件名列表
cookies_file_name = [
    [
        './cookies/phone_curl/phone_curl_dmall.sh',
        './cookies/phone_curl/phone_curl_hiboos.sh',
        './cookies/phone_curl/phone_curl_jddj.sh',
        './cookies/phone_curl/phone_curl_mtwm.sh',
        './cookies/phone_curl/phone_curl_ele.sh',
    ], [
        './cookies/chrome_curl/curl_dmall.sh',
        './cookies/chrome_curl/curl_hiboos.sh',
        './cookies/chrome_curl/curl_jddj.sh',
        './cookies/chrome_curl/curl_mtwm.sh',
        './cookies/chrome_curl/curl_ele.sh'
    ]
]
for i in range(5):
    #默认的rt方式打开文件在文件不存在时会报异常，所以要上一个try
    try:
        file_in = open(cookies_file_name[0][i])
        text_cookies = file_in.read()
        file_in.close()
    except FileNotFoundError:
        print('错误！文件{}不存在！！！'.format(cookies_file_name[0][i]))
        exit()
    if text_cookies == '':
        continue
    text_cookies = text_cookies.replace(' ','')
    in_s = text_cookies.index("'") + 1
    in_e = text_cookies.index("'", in_s)
    text_cookies = text_cookies[in_s: in_e - 1]
    temp_cookies = text_cookies.split(';')
    temp_cookies = [i.split('=') for i in temp_cookies]
    dict_cookies = {i[0]: i[1] for i in temp_cookies}
    text_cookies = ''
    for j, k in dict_cookies.items():
        text_cookies += j
        text_cookies += '='
        text_cookies += k
        text_cookies += '; '
    try:
        file_in = open(cookies_file_name[1][i])
        text_curl = file_in.read()
        file_in.close()
    except FileNotFoundError:
        print('错误！文件{}不存在！！！'.format(cookies_file_name[0][i]))
        exit()
    in_s = text_curl.lower().index('cookie: ') + 8
    in_e = text_curl.index("'", in_s)
    text_curl = text_curl[: in_s] + text_cookies[: -2] + text_curl[in_e: ]
    file_in = open(cookies_file_name[1][i], 'w')
    file_in.write(text_curl)
    file_in.close()
    file_in = open(cookies_file_name[0][i], 'w')
    file_in.close()
